package com.advertisementsystem.Controller;

import com.advertisementsystem.Dto.LoginUser;
import com.advertisementsystem.Dto.UserQueryDTO;
import com.advertisementsystem.Servie.Impl.EmailService;
import com.advertisementsystem.Servie.UserService;
import com.advertisementsystem.entity.User;
import com.advertisementsystem.Exception.ResponseResult;
import com.advertisementsystem.utils.RedisCache;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 创建新用户
     *
     * @param user 用户信息
     * @return 创建成功的用户信息
     */
    @PostMapping
    public ResponseResult<User> createUser(@RequestBody User user) {
        try {
            return ResponseResult.success(userService.createUser(user));
        } catch (Exception e) {
            log.error("创建用户失败", e);
            return ResponseResult.error(e.getMessage());
        }
    }


    /**
     * 删除用户
     *
     * @param id 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseResult<Boolean> deleteUser(@PathVariable Long id) {
        try {
            return ResponseResult.success(userService.deleteUser(id));
        } catch (Exception e) {
            log.error("删除用户失败", e);
            return ResponseResult.error(e.getMessage());
        }
    }

    /**
     * 根据ID获取用户详情
     *
     * @param id 用户ID
     * @return 用户详细信息
     */
    @GetMapping("/{id}")
    public ResponseResult<User> getUserById(@PathVariable Long id) {
        try {
            return ResponseResult.success(userService.getUserById(id));
        } catch (Exception e) {
            log.error("获取用户详情失败", e);
            return ResponseResult.error(e.getMessage());
        }
    }


    /**
     * 更新用户信息
     *
     * @param user 需要更新的用户信息
     * @return 更新后的用户信息
     */
    @PutMapping
    public ResponseResult<User> updateUser(@RequestBody User user) {
        try {
            return ResponseResult.success(userService.updateUser(user));
        } catch (Exception e) {
            log.error("更新用户失败", e);
            return ResponseResult.error(e.getMessage());
        }
    }
    /**
     * 条件分页查询用户列表
     *
     * @param queryDTO 查询条件，包含：
     *                 - username：用户名（模糊查询）
     *                 - nickname：昵称（模糊查询）
     *                 - phone：手机号（模糊查询）
     *                 - email：邮箱（模糊查询）
     *                 - status：状态（精确查询）
     *                 - roleType：角色类型（精确查询）
     *                 - pageNum：页码
     *                 - pageSize：每页记录数
     * @return 分页用户列表
     */
    @GetMapping
    public ResponseResult<Page<User>> listUsers(UserQueryDTO queryDTO) {
        try {
            return ResponseResult.success(userService.listUsers(queryDTO));
        } catch (Exception e) {
            log.error("查询用户列表失败", e);
            return ResponseResult.error(e.getMessage());
        }
    }

    /**
     * 更新用户状态
     *
     * @param id     用户ID
     * @param status 新状态值
     * @return 更新结果
     */
    @PutMapping("/{id}/status")
    public ResponseResult<Boolean> updateUserStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        try {
            return ResponseResult.success(userService.updateUserStatus(id, status));
        } catch (Exception e) {
            log.error("更新用户状态失败", e);
            return ResponseResult.error(e.getMessage());
        }
    }

    /**
     * 修改用户密码
     *
     * @param id          用户ID
     * @param newPassword 新密码
     * @return 修改结果
     */
    @PutMapping("/{id}/password")
    public ResponseResult<Boolean> updatePassword(
            @PathVariable Long id,
            @RequestParam String newPassword) {
        try {
            return ResponseResult.success(userService.updatePassword(id, newPassword));
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return ResponseResult.error(e.getMessage());
        }
    }






        private static final String RESET_CODE_PREFIX = "password_reset_code:";
        private static final String RESET_TOKEN_PREFIX = "password_reset_token:";
        private static final long CODE_EXPIRE_TIME = 10 * 60; // 验证码10分钟过期
        private static final long TOKEN_EXPIRE_TIME = 30 * 60; // 令牌30分钟过期

        /**
         * 发送重置密码的验证码
         */
        @PostMapping("/reset/code")
        public ResponseResult<Void> sendResetCode(@RequestBody Map<String, String> requestMap) {
            String username = requestMap.get("username");
            if (StringUtils.isEmpty(username)) {
                return ResponseResult.error(400, "用户名不能为空");
            }

            // 根据用户名查询用户
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return ResponseResult.error(404, "用户不存在");
            }

            // 获取用户邮箱
            String email = "3396551420@qq.com";
            if (StringUtils.isEmpty(email)) {
                return ResponseResult.error(400, "该用户未设置邮箱，无法重置密码");
            }

            // 生成6位随机验证码
            String verificationCode = generateRandomCode(6);


            redisCache.setCacheObject(RESET_TOKEN_PREFIX + username, verificationCode, (int) CODE_EXPIRE_TIME,
                    TimeUnit.SECONDS);
            // 将验证码存入Redis，设置过期时间
            // redisTemplate.opsForValue().set(
            //         RESET_CODE_PREFIX + username,
            //         verificationCode,
            //         CODE_EXPIRE_TIME,
            //         TimeUnit.SECONDS
            // );

            // 发送邮件
            String subject = "广告营销管理系统-密码重置验证码";
            String content = "您好，您正在进行密码重置操作，验证码为：" + verificationCode + "，有效期10分钟。如非您本人操作，请忽略此邮件。";
            emailService.sendSimpleMail(email, subject, content);

            return ResponseResult.success();
        }

        /**
         * 验证重置密码的验证码
         */
        @PostMapping("/reset/verify")
        public ResponseResult<String> verifyResetCode(@RequestBody Map<String, String> requestMap) {
            String username = requestMap.get("username");
            String code = requestMap.get("code");

            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(code)) {
                return ResponseResult.error(400, "用户名或验证码不能为空");
            }

            // 从Redis获取验证码
            // String storedCode = redisTemplate.opsForValue().get(RESET_CODE_PREFIX + username);
            String storedCode = redisCache.getCacheObject(RESET_TOKEN_PREFIX + username);
            if (storedCode == null) {
                return ResponseResult.error(400, "验证码已过期，请重新获取");
            }

            // 验证码不匹配
            if (!storedCode.equals(code)) {
                return ResponseResult.error(400, "验证码错误");
            }

            // 验证通过，生成一个token
            String token = UUID.randomUUID().toString();

            // 将token存入Redis，设置过期时间
            redisCache.setCacheObject(RESET_TOKEN_PREFIX + username, token, (int) TOKEN_EXPIRE_TIME,TimeUnit.SECONDS);



            // 删除验证码，防止重复使用
            redisCache.deleteObject(RESET_CODE_PREFIX + username);

            return ResponseResult.success(token);
        }

        /**
         * 重置密码
         */
        @PostMapping("/reset")
        public ResponseResult<Void> resetPassword(@RequestBody Map<String, String> requestMap) {
            String username = requestMap.get("username");
            String newPassword = requestMap.get("newPassword");
            String token = requestMap.get("token");

            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(token)) {
                return ResponseResult.error(400, "参数不完整");
            }

            // 从Redis获取token
            ///String storedToken = redisTemplate.opsForValue().get(RESET_TOKEN_PREFIX + username);
            String storedToken = redisCache.getCacheObject(RESET_TOKEN_PREFIX + username);
            if (storedToken == null) {
                return ResponseResult.error(400, "重置链接已过期，请重新获取验证码");
            }

            // token不匹配
            if (!storedToken.equals(token)) {
                return ResponseResult.error(400, "重置链接无效");
            }

            // 根据用户名查询用户
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return ResponseResult.error(404, "用户不存在");
            }

            // 加密新密码
            String encodedPassword = passwordEncoder.encode(newPassword);

            // 更新用户密码
            user.setPassword(encodedPassword);
            userService.updateUser(user);

            // 删除token，防止重复使用
            redisCache.deleteObject(RESET_TOKEN_PREFIX + username);
            // redisTemplate.delete(RESET_TOKEN_PREFIX + username);

            return ResponseResult.success();
        }

        /**
         * 生成随机验证码
         */
        private String generateRandomCode(int length) {
            StringBuilder sb = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < length; i++) {
                sb.append(random.nextInt(10));
            }
            return sb.toString();
        }


}